package com.jp.knowledge.activity;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;

import com.github.anzewei.parallaxbacklayout.ParallaxHelper;
import com.jiayen.cache.FileCacheManager;
import com.jiayen.util.ToasUtil;
import com.jiayen.view.TabItemView;
import com.jp.knowledge.R;
import com.jp.knowledge.broad.LocalBroadCast;
import com.jp.knowledge.comm.BaseActivity;
import com.jp.knowledge.comm.JpApplication;
import com.jp.knowledge.comm.SlidingActivity;
import com.jp.knowledge.command.implement.FaXianShouYe;
import com.jp.knowledge.command.implement.GangWeiZhiShiPaiXu;
import com.jp.knowledge.command.implement.GangWeiZhiShiShouYe;
import com.jp.knowledge.command.implement.JinRiZhiShiShouYe;
import com.jp.knowledge.dialog.CommDialog;
import com.jp.knowledge.dialog.WelDialog;
import com.jp.knowledge.fragment.DailyKnowledgeFragment;
import com.jp.knowledge.fragment.FindFragment;
import com.jp.knowledge.fragment.JobknowledgeFragment;
import com.jp.knowledge.fragment.KnowledgeFragment;
import com.jp.knowledge.fragment.MyFragment;
import com.jp.knowledge.fragment.PositionKnowleageFragment;
import com.jp.knowledge.fragment.TeamCircleMainFragment;
import com.jp.knowledge.logic.InviteFriendsLogic;
import com.jp.knowledge.logic.PersonLogic;
import com.jp.knowledge.model.UserData;
import com.jp.knowledge.service.LatestStateService;
import com.jp.knowledge.util.L;

import java.util.ArrayList;
import java.util.List;

import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class  JpMainActivity extends BaseActivity implements View.OnClickListener {

    private TabItemView toutiao;
    private TabItemView guanzhu;
    private TabItemView personItem;
    private TabItemView foundItem;
    private TabItemView jingbao;
    private Fragment[] fragments;
    private TabItemView[] itemViews;

    private FragmentManager manager;
    private FragmentTransaction transaction;
    private FrameLayout contentLayout;

    private int lastFrament = 0;        // 记录最后显示的fragment的位置
    private CommDialog exitDialog;
    private int size = 4;

    private LocalBroadCast localBroadCast;
    private LocalBroadcastManager localBroadcastManager;

    private int[] normalImages = new int[]{R.mipmap.bottombar_homepage, R.mipmap.bottombar_repository, R.mipmap.bottombar_discovery, R.mipmap.bottombar_my};
    private int[] selectImages = new int[]{R.mipmap.bottombar_homepage_blue, R.mipmap.bottombar_repository_blue, R.mipmap.bottombar_discovery_blue, R.mipmap.bottombar_my_blue};

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        new PersonLogic(JpMainActivity.this).getUserData();
        new InviteFriendsLogic(JpMainActivity.this).getInviteData();
        startService(new Intent(this, LatestStateService.class));

        super.onCreate(savedInstanceState);

        switchToFragment(getIntent().getStringExtra("command"));
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        switchToFragment(intent.getStringExtra("command"));
    }

    private void switchToFragment(String command){
        if(JinRiZhiShiShouYe.class.getSimpleName().equals(command)){            // 今日知识首页
            onClick(itemViews[0]);
        } else if(GangWeiZhiShiShouYe.class.getSimpleName().equals(command)){   // 岗位知识首页
            onClick(itemViews[1]);
        } else if(GangWeiZhiShiPaiXu.class.getSimpleName().equals(command)){    // 岗位知识排序
            ((JobknowledgeFragment)fragments[1]).showDragDialog();
            onClick(itemViews[1]);
        } else if(FaXianShouYe.class.getSimpleName().equals(command)){          // 发现首页
            onClick(itemViews[2]);
        }
    }

    @Override
    protected void onDestroy() {
        localBroadcastManager.unregisterReceiver(localBroadCast);
        stopService(new Intent(this, LatestStateService.class));
        super.onDestroy();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {

    }

    @Override
    protected int getResourceId() {
        return R.layout.activity_jp_main;
    }

    @Override
    protected void init() {

        if(checkPermission(PERMISSION[0])){
            requesPermission();
        }

        initTabItem();

        manager = getSupportFragmentManager();
        fragments = new Fragment[size];

//        fragments[0] = new DailyKnowledgeFragment();
//        fragments[1] = new JobknowledgeFragment();
//        fragments[2] = new TeamCircleMainFragment();
//        fragments[3] = new FindFragment();
//        fragments[4] = new MyFragment();

        fragments[0] = new DailyKnowledgeFragment();
        fragments[1] = new JobknowledgeFragment();
        fragments[2] = new FindFragment();
        fragments[3] = new MyFragment();

        itemViews = new TabItemView[size];
        itemViews[0] = toutiao;
        itemViews[1] = guanzhu;
        itemViews[2] = jingbao;
        itemViews[3] = foundItem;

        if(application.isLogin()) {
            normalImages[normalImages.length - 1] = R.mipmap.bottombar_my;
            selectImages[selectImages.length - 1] = R.mipmap.bottombar_my_blue;
        } else{
            normalImages[normalImages.length - 1] = R.mipmap.bottombar_my_unlogin;
            selectImages[selectImages.length - 1] = R.mipmap.bottombar_my_unlogin_blue;
        }

        String[] itemNames = new String[]{"今日知识", "岗位知识", "发现", "我的"};
        for (int i = 0; i < size; i++) {
            itemViews[i].setname(itemNames[i]);
            itemViews[i].setIcon(normalImages[i]);
            itemViews[i].setOnClickListener(this);
        }
        if(!application.isLogin())
            itemViews[3].setname("未登录");

        initAllFragment();//默认加载所有fragment

        //默认显示第一个
        manager.beginTransaction().add(R.id.content, fragments[0]).commit();
        itemViews[0].setNameColor(getResources().getColor(R.color.theme_color));
        itemViews[0].setIcon(selectImages[0]);
//        setFullScreen(true);

        //初始标题内容
        exitDialog = new CommDialog(mContext);
        exitDialog.setContent("你确定要退出荐识吗？");
        exitDialog.setLeft("取消");
        exitDialog.setRight("确定");
        exitDialog.setRightListener(this);

        initBroadCast();
        // 安卓 6.0 以上申请SD卡权限
        requestExternalStoragePremission();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    /* 默认加载所有fragmeng */
    private void initAllFragment() {
        int size = fragments.length;
        for (int i = 1; i <size ; i++) {
            if (!fragments[i].isAdded()) {
                manager.beginTransaction().add(R.id.content, fragments[i]).show(fragments[i]).commit();
            }
            manager.beginTransaction().hide(fragments[i]).commit();
        }
    }

    /**
     * 设置全屏  状态栏透明
     */
    private void setFullScreen(boolean flag){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            if(flag){
                getWindow().setStatusBarColor(Color.TRANSPARENT);
                getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
            }
        }
    }

    /* 初始化tabItem */
    private void initTabItem() {
        contentLayout = (FrameLayout) findViewById(R.id.content);
        toutiao = (TabItemView) findViewById(R.id.toutiao);
        guanzhu = (TabItemView) findViewById(R.id.guangzhu);
        jingbao = (TabItemView) findViewById(R.id.jingbao);
        foundItem = (TabItemView) findViewById(R.id.found);
        personItem = (TabItemView) findViewById(R.id.person);

        personItem.setVisibility(View.GONE);
    }

    private void initBroadCast(){
        localBroadcastManager = LocalBroadcastManager.getInstance(this);
        localBroadCast = new LocalBroadCast(new LocalBroadCast.BroadCastCallBack() {
            @Override
            public void done(Context context, Intent intent) {
                String action = intent.getAction();
                switch (action){
                    case LocalBroadCast.GET_LOGIN_INFO:
                        if(application.isLogin()){
                            normalImages[normalImages.length - 1] = R.mipmap.bottombar_my;
                            selectImages[selectImages.length - 1] = R.mipmap.bottombar_my_blue;
                            itemViews[3].setname("我的");
                            break;
                        }
                    case LocalBroadCast.LOGOUT_SUCCESS_BROD:
                        normalImages[normalImages.length - 1] = R.mipmap.bottombar_my_unlogin;
                        selectImages[selectImages.length - 1] = R.mipmap.bottombar_my_unlogin_blue;
                        itemViews[3].setname("未登录");
                        break;
                }
                if(lastFrament == 3)
                    itemViews[3].setIcon(selectImages[3]);
                else
                    itemViews[3].setIcon(normalImages[3]);
            }
        });
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(LocalBroadCast.GET_LOGIN_INFO);
        intentFilter.addAction(LocalBroadCast.LOGOUT_SUCCESS_BROD);
        localBroadcastManager.registerReceiver(localBroadCast, intentFilter);
    }

    public void onClick(View view) {
        if(view.getId()==R.id.right_btn){
            exitDialog.dismiss();
            application.finish();
        }else if(view.getId()==R.id.icon_serach){
            startActivity(new Intent(mContext,SearchActivity.class));
        }else{
            for (int i = 0; i < size; i++) {
                if (view == itemViews[i]) {
                    showFragment(i);
                    break;
                }
            }
        }
    }

    /* 显示Fragment */
    private void showFragment(int position) {
        // 防止重复点击
        if (position != lastFrament) {
            contentLayout.setVisibility(View.VISIBLE);
            transaction = manager.beginTransaction();
            if (fragments[position].isAdded()) {
                transaction.hide(fragments[lastFrament]).show(fragments[position]);
            } else {
                transaction.hide(fragments[lastFrament]).add(R.id.content, fragments[position]);
            }
            transaction.commit();

            itemViews[position].setNameColor(getResources().getColor(R.color.theme_color));
            setFullScreen(false);
            itemViews[position].setIcon(selectImages[position]);

            itemViews[lastFrament].setNameColor(getResources().getColor(R.color.bottom_bar_gray));
            itemViews[lastFrament].setIcon(normalImages[lastFrament]);
        }
        lastFrament = position;
    }

    @Override
    public void onBackPressed() {
        if(exitDialog!=null){
            exitDialog.show();
        }
    }

    private static final int REQUEST_EXTERNAL_STORAGE_PREMISSION = 0x01;
    // 安卓 6.0 需要申请存储卡权限
    private void requestExternalStoragePremission(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if(ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                    && ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        REQUEST_EXTERNAL_STORAGE_PREMISSION);
            }
        }
    }

    //申请读取手机状态权限
    private static String[] PERMISSION= {Manifest.permission.READ_PHONE_STATE};

    /**
     * 检查权限
     * @param permission
     * @return
     */
    private boolean checkPermission(String permission){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            return ContextCompat.checkSelfPermission(mContext, permission) ==
                    PackageManager.PERMISSION_DENIED;
        }
        return  false;
    }

    /***
     * 请求权限
     */
    private void requesPermission(){
        ActivityCompat.requestPermissions(this,PERMISSION,0x12);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_EXTERNAL_STORAGE_PREMISSION && grantResults.length > 0){
            for(int grantResult : grantResults){
                if(grantResult != PackageManager.PERMISSION_GRANTED){
                    ToasUtil.toast(this, "抱歉，你没有权限访问SD卡");
                    return;
                }
            }
        }
    }
}
